{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "14bbcdbd",
   "metadata": {},
   "source": [
    "# 事件\n",
    "1. 事件是基于委托的存在\n",
    "2. 事件是委托的安全包裹\n",
    "3. 事件让委托更具安全性\n",
    "4. 事件是一种特殊的变量类型\n",
    "# 事件的使用\n",
    "1. 事件是作为成员变量存在与类中,不能作为临时变量在函数中使用\n",
    "2. 事件的使用和委托类似\n",
    "# 事件相对于委托的区别\n",
    "1. 不能在类外部赋值\n",
    "2. 不能在类外部调用\n",
    "3. 事件只能作为成员存在与类和接口及结构体中\n",
    "# 事件的作用\n",
    "1. 防止外部随意指控委托\n",
    "2. 防止外部随意调用委托\n",
    "3. 事件相对于委托进行一次封装,让其更安全"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "834ec9e7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "TestFunc called\n",
      "TestFunc called\n",
      "TestFunc called\n",
      "TestFunc called\n",
      "Anonymous function called\n",
      "TestFunc called\n",
      "TestFunc called\n",
      "Anonymous function called\n"
     ]
    }
   ],
   "source": [
    "using System;\n",
    "class TestClass{\n",
    "    public Action myFunc;\n",
    "\n",
    "    public event Action myEvent;\n",
    "\n",
    "    public void TestFunc(){\n",
    "        Console.WriteLine(\"TestFunc called\");\n",
    "    }\n",
    "\n",
    "    public TestClass(){\n",
    "        myFunc = TestFunc;\n",
    "        myEvent = TestFunc;\n",
    "        myEvent += myFunc; //在类内部,事件可以加委托\n",
    "        this.myFunc.Invoke();\n",
    "        myEvent();\n",
    "    }\n",
    "\n",
    "    public void Awake(){\n",
    "        myEvent.Invoke();\n",
    "    }\n",
    "}\n",
    "\n",
    "TestClass test = new TestClass();\n",
    "\n",
    "test.myFunc += () => Console.WriteLine(\"Anonymous function called\");\n",
    "test.myFunc.Invoke();\n",
    "test.myFunc = null; // 取消委托\n",
    "test.myEvent += () => Console.WriteLine(\"Anonymous function called\");\n",
    "test.Awake();\n",
    "// test.myEvent(); // 不能在类外部调用\n",
    "// test.myEvent = null; // 取消事件 报错,事件不能再类外赋值"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".NET (C#)",
   "language": "C#",
   "name": ".net-csharp"
  },
  "language_info": {
   "name": "polyglot-notebook"
  },
  "polyglot_notebook": {
   "kernelInfo": {
    "defaultKernelName": "csharp",
    "items": [
     {
      "aliases": [],
      "name": "csharp"
     }
    ]
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
